<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>自定义事件监听、发布订阅</title>
</head>

<body>
    <script>
        // function fn1(e) {
        //     console.log('f1', e.detail);
        // }

        // function fn2(e) {
        //     console.log('f2', e.detail);
        // }

        // let event = new EventTarget();

        // // 创建事件
        // event.addEventListener("myevent", fn1);
        // event.addEventListener("myevent", fn2);

        // setTimeout(() => {
        //     // 派发事件
        //     event.dispatchEvent(new CustomEvent("myevent", {
        //         detail: 'tianditu'
        //     }))
        // }, 1000);


        function fn1() {
            console.log('f1');
        }

        function fn2() {
            console.log('f2');
        }

        // 收集器
        class Dep {
            constructor() {
                this.subs = [];
            }

            addSub(sub) {
                this.subs.push(sub);
            }

            notify() {
                this.subs.forEach(sub => {
                    sub.update();
                })
            }
        }

        class Watcher {
            constructor(cb) {
                this.cb = cb;
            }

            update() {
                this.cb();
            }
        }

        let dep = new Dep();
        dep.addSub(new Watcher(fn1));
        dep.addSub(new Watcher(fn2));

        setTimeout(() => {
            dep.notify();
        }, 500);
    </script>
</body>

</html>